package top.lyc829.zzl_android.ui.team.team_detail;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.data.DateUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityTeamDetailBinding;
import top.lyc829.zzl_android.logic.bean.ActivityBean;
import top.lyc829.zzl_android.logic.bean.BaseDetailBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.FellowType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.message.praise.NoticePraiseActivity;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.team.my_team.activity.MyActivityAdapter;

public class TeamDetailActivity extends AppCompatActivity {

    private TeamDetailViewModel mViewModel;
    private ActivityTeamDetailBinding binding;
    private ActivityAdapter adapter;

    TitleBar.ImageAction collectionIcon;

    MiniLoadingDialog mMiniLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTeamDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mViewModel = new ViewModelProvider(this).get(TeamDetailViewModel.class);
        mViewModel.getTeamId().setValue(getIntent().getIntExtra("team_id", -1));

        mMiniLoadingDialog =  WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.updateMessage("加载中");
        mMiniLoadingDialog.setCancelable(false);

        collectionIcon = new TitleBar.ImageAction(R.drawable.ic_un_collection) {
            @Override
            public void performAction(View view) {
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    return;
                }else if (mViewModel.getIsFellowLiveData().getValue() != null) {
                    mMiniLoadingDialog.show();
                    if(mViewModel.getIsFellowLiveData().getValue().equals(0)) {
                        Network.attention(Utils.getUserId(), FellowType.TEAM, mViewModel.getTeamId().getValue(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resultStr = res.body().string();
                                ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                                if (resultBean.getCode().equals(200)) {

                                    runOnUiThread(() -> {
                                        mMiniLoadingDialog.dismiss();
                                        mViewModel.getIsFellowLiveData().setValue(1);
                                    });
                                } else {
                                    failed(new IOException());
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    mMiniLoadingDialog.dismiss();
                                    Utils.showToastSync("关注失败");
                                });


                            }
                        });

                    } else if (mViewModel.getIsFellowLiveData().getValue().equals(1)) {
                        Network.unAttention(Utils.getUserId(), FellowType.TEAM, mViewModel.getTeamId().getValue(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resultStr = res.body().string();
                                ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        mMiniLoadingDialog.dismiss();
                                        mViewModel.getIsFellowLiveData().setValue(0);
                                    });
                                } else {
                                    failed(new IOException());
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    mMiniLoadingDialog.dismiss();
                                    Utils.showToastSync("取消关注失败");
                                });
                            }
                        });

                    }
                }



            }
        };

        binding.mTitleBarTeamDetail.addAction(collectionIcon);

        initRecycler();

        initData();
        observer();
        clickListener();
    }

    private void initRecycler() {
        adapter = new ActivityAdapter();
        binding.teamDetailRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.teamDetailRecycler.setAdapter(adapter);
        adapter.setList(null);
    }

    private void observer() {
        mViewModel.getTeamId().observe(this, integer -> {
            mViewModel.getTeamInfo(integer);
            mViewModel.getTeamActivities(integer);
            //mViewModel.getIsJoinTeam(Utils.getUserId(), integer);
            mViewModel.getMyTeamIdFromServer(Utils.getUserId());

            mViewModel.getFellowRelationShip(Utils.getUserId(), FellowType.TEAM, integer);
        });

        mViewModel.getTeamInfoLiveData().observe(this, myTeamInfoBean -> {
            binding.mTitleBarTeamDetail.setTitle(myTeamInfoBean.getName());

            binding.teamDetailLeaderUsername.setText(myTeamInfoBean.getLeader().getNickname());
            binding.teamDetailName.setText(myTeamInfoBean.getName());
            binding.teamDetailType.setText(getResources().getStringArray(R.array.team_type)[myTeamInfoBean.getType()]);
            binding.teamDetailIntroduction.setText(myTeamInfoBean.getIntroduction());
            Glide.with(this)
                    .load(myTeamInfoBean.getHeaderImg())
                    .into(binding.teamDetailHeaderImg);
            Glide.with(this)
                    .load(myTeamInfoBean.getLeader().getAvatarUrl())
                    .into(binding.teamDetailLeaderAvatar);

            if (myTeamInfoBean.getLeader().getId().equals(Utils.getUserId())) {
                binding.btnJoinTeam.setVisibility(View.GONE);
            }
        });

        mViewModel.getActivitiesLiveData().observe(this, activityBeans -> {
            adapter.setList(activityBeans);
            for (ActivityBean activity : activityBeans) {
                mViewModel.getBasesInfo(activity.getBaseId());
            }
        });

        mViewModel.getBaseBeanLiveData().observe(this, baseDetailBeans -> {
            if (baseDetailBeans == null || mViewModel.getActivitiesLiveData().getValue() == null) {
                return;
            }
            if (baseDetailBeans.size() == mViewModel.getActivitiesLiveData().getValue().size()) {

                for (int i = 0; i < baseDetailBeans.size(); i++) {
                    ActivityBean activityBean = adapter.getItem(i);
                    activityBean.setBaseName(baseDetailBeans.get(i).getTitle());
                    adapter.setData(i, activityBean);
                }
            }
        });

        mViewModel.getMyTeamStateLiveData().observe(this, myTeamState -> {

            if (myTeamState == null) {
                return;
            }

            if (myTeamState.getApplyState().equals("1")) {
                // 申请的就是这个团的情况且在申请中
                if (myTeamState.getTeamId().equals(mViewModel.getTeamId().getValue())) {
                    binding.btnJoinTeam.setText("申请中");
                    binding.btnJoinTeam.setBackgroundResource(R.drawable.btn_un_attentioned);
                } else {    // 在申请中，但不是这个团队
                    binding.btnJoinTeam.setText("加入团队");
                    binding.btnJoinTeam.setBackgroundResource(R.drawable.btn_attentioned);
                    binding.btnJoinTeam.setEnabled(false);
                }
            } else if (myTeamState.getApplyState().equals("2")) {
                binding.btnJoinTeam.setText("加入团队");
                binding.btnJoinTeam.setBackgroundResource(R.drawable.btn_attentioned);
                binding.btnJoinTeam.setEnabled(false);
            }
        });


        mViewModel.getIsFellowLiveData().observe(this, integer -> {
            if (integer.equals(1)) {
                ((ImageView)binding.mTitleBarTeamDetail.getViewByAction(collectionIcon))
                        .setImageResource(R.drawable.ic_collection);
            } else {
                ((ImageView)binding.mTitleBarTeamDetail.getViewByAction(collectionIcon))
                        .setImageResource(R.drawable.ic_un_collection);
            }
        });
//
//        mViewModel.getIsJoinTeamLiveData().observe(this, aBoolean -> {
//            if (aBoolean) {
//                binding.btnJoinTeam.setText("已参加");
//                binding.btnJoinTeam.setBackgroundResource(R.drawable.btn_attentioned);
//                binding.btnJoinTeam.setEnabled(false);
//            } else {
//                binding.btnJoinTeam.setText("加入团队");
//                binding.btnJoinTeam.setBackgroundResource(R.drawable.btn_un_attentioned);
//                binding.btnJoinTeam.setEnabled(true);
//            }
//        });
    }

    private void initData() {

    }

    private void clickListener() {
        binding.mTitleBarTeamDetail.setLeftClickListener(v -> finish());

        adapter.setOnItemClickListener((adapter1, view, position) -> {
            int baseId = adapter.getData().get(position).getBaseId();
            Intent intent = new Intent(this, BaseDetailActivity.class);
            intent.putExtra("id", baseId);
            startActivity(intent);
        });

        binding.btnJoinTeam.setOnClickListener(v -> {
            if (!Utils.isLogin()) {
                Utils.showToast("请先登录");
            } else if (mViewModel.getTeamId().getValue() != null) {
                if (binding.btnJoinTeam.getText().toString().equals("加入团队")) {
                    List<String> items = new ArrayList<>();
                    if (mViewModel.getActivitiesLiveData().getValue() != null) {
                        for (ActivityBean activityBean : mViewModel.getActivitiesLiveData().getValue()) {
                            if (activityBean.getIsDelete().equals(0)) {
                                items.add(activityBean.getName());
                            }
                        }
                    }
                    if (items.size() == 0) {
                        Utils.showToast("所有活动已结束");
                        return;
                    }

                    new MaterialDialog.Builder(this)
                            .title("活动选择")
                            .items(items)
                            .itemsCallbackSingleChoice(
                                    0,
                                    (dialog, itemView, which, text) -> {
                                        joinTeam(which);
                                        return true;
                                    })
                            .positiveText("选择")
                            .negativeText("取消")
                            .show();
                } else if (binding.btnJoinTeam.getText().toString().equals("申请中")) {
                    exitTeam();
                }


            } else if (mViewModel.getTeamId().getValue() == null) {
                Utils.showToast("加入失败");
                Utils.Sout("lost teamId");
            }
        });


        binding.teamDetailLeaderAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(TeamDetailActivity.this, OtherUserDetailActivity.class);
            intent.putExtra("id", mViewModel.getTeamInfoLiveData().getValue().getLeader().getId());
            startActivity(intent);
        });
    }

    //退出团队
    private void exitTeam() {

    }

    private void joinTeam(int index) {

        ActivityBean activityBean = adapter.getItem(index);

        if (DateUtils.getNowMills() - Long.parseLong(activityBean.getEndDate()) > 0) {
            Utils.showToast("活动已经结束");
            return;
        }

        Network.joinTeam(Utils.getUserId(), mViewModel.getTeamId().getValue(),activityBean.getId(), new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                ResultBean<Void> resultBean = JsonUtilNew
                        .fromJsonObject(res.body().string(), Void.class);

                if (resultBean.getCode().equals(200)) {

                    runOnUiThread(() -> {
                        mViewModel.getIsJoinTeamLiveData().setValue(true);
                        new MaterialDialog.Builder(TeamDetailActivity.this)
                                .content("申请成功")
                                .positiveText("是")
                                .show();
                        mViewModel.getMyTeamIdFromServer(Utils.getUserId());
                    });

                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }

    @Override
    protected void onDestroy() {
        mMiniLoadingDialog.recycle();
        super.onDestroy();
    }
}